import {Image, StyleSheet, View, Text, TouchableOpacity} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import {useEffect, useState} from "react";
import avator from "@/assets/images/me/avator.png";
import addGroupAdmin from "@/assets/images/chatIcon/addGroupAdmin.png"
import {useActionSheet} from "@expo/react-native-action-sheet";
import increateGroupIcon from "@/assets/images/chatIcon/increateGroupIcon.png"
import {useConversationStore} from "@/hooks/im/conversation";
import {showToast} from "@/utils/rootToast";
import { GroupVerifty, RoleLevelEnum } from "@/types/chat"



export default function setGroupAdminScreen() {

    const router = useRouter();
    const [toggleEdite, setToggleEdite] = useState(false);
    const { showActionSheetWithOptions } = useActionSheet();
    const [list, setList] = useState([])

    const options = ['群成员邀请无需验证', '需要发送验证消息', '允许所有人加群', '取消'];

    const currentGroupInfo = useConversationStore(state => state.currentGroupInfo);
    const currentGroupList = useConversationStore((state) => state.currentGroupList);
    const setCurrentGroupListFuc = useConversationStore((state) => state.setCurrentGroupListFuc);
    const postGroupInfoFuc = useConversationStore((state) => state.postGroupInfoFuc)
    const postGroupMemberInfoFuc = useConversationStore((state) => state.postGroupMemberInfoFuc)
    const getCurrentGroupMenmberInfoByReq = useConversationStore((state) => state.getCurrentGroupMenmberInfoByReq)

    useEffect(() => {
        const tmpList = currentGroupList;
        setList(tmpList);

    }, []);

    useEffect(() => {
        setList(currentGroupList);
        console.log('currentGroupList', currentGroupList);
    }, [currentGroupList])

    const openActionSheet = () => {

        const cancelButtonIndex = 3;

        showActionSheetWithOptions(
            {
                options,
                cancelButtonIndex,
            },
            (buttonIndex) => {
                switch (buttonIndex) {
                    case 0:
                        console.log('群成员邀请无需验证');
                        postGroupInfoFuc(GroupVerifty.ApplyNeedInviteNot)
                        break;
                    case 1:
                        postGroupInfoFuc(GroupVerifty.AllNeed)
                        console.log('需要发送验证消息');
                        break;
                    case 2:
                        postGroupInfoFuc(GroupVerifty.AllNot)
                        console.log('允许所有人加群');
                        break;
                    case 3:
                        console.log('取消 selected');
                        break;
                    default:
                        break;
                }
            }
        );
    };

    const goGroupAdmin  = function () {
        if (!toggleEdite) {
            return showToast("请点击右上角编辑！");
        };
        router.push("/groupSetting/groupAdmin")
    };

    const removeGroupAdmin = function (id) {
        const groupList = list;
        const index = groupList.findIndex((item) => item.userID == id);
        Reflect.set(groupList[index], "select", false);

        console.log('groupList', groupList);
        setCurrentGroupListFuc(groupList);
        setList(groupList)
    };

    const computedAdmin = function () {
        const countList = currentGroupList.filter((item, index) => (item.roleLevel == RoleLevelEnum.Admin || item?.select));
        return countList.length;
    };

    const backPage = function () {
        const groupList = list;
        const tmpList = groupList.map((item, index) => {
            if (item.roleLevel == RoleLevelEnum.Nomal && item.select) {
                delete item.select;
            };
            if (item.roleLevel == RoleLevelEnum.Admin && !item.select) {
                item.select = true;
            };
            return item;
        });


        setCurrentGroupListFuc(tmpList);
        router.back()
    };

    const addAdminGroup = function () {
        const groupList = list;
        groupList.forEach((item, index) => {
           if (item.select) {
               const info = {
                   userID: item.userID,
                   roleLevel: RoleLevelEnum.Admin,
               };
               postGroupMemberInfoFuc(info);
           };

           if (item.roleLevel == RoleLevelEnum.Admin && !item.select) {
               const info = {
                   userID: item.userID,
                   roleLevel: RoleLevelEnum.Nomal,
               };
               postGroupMemberInfoFuc(info);
           };
           if (index + 1 == groupList.length) {
               setTimeout(() => {
                   getCurrentGroupMenmberInfoByReq(currentGroupInfo.groupID);
               }, 500)
           };
        });
        setToggleEdite(false)
    };

    const enableAdmin = function () {
        const tmpList =currentGroupList.filter((item) => item.roleLevel == RoleLevelEnum.Admin);
        return tmpList.length;
    };

    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '设置管理员', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#f7f7f7', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={backPage}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                    headerRight: () => (
                        !toggleEdite ? (
                            <TouchableOpacity onPress={() => setToggleEdite(true)}>
                                <Text style={{ color: "#EC6138" }}>编辑</Text>
                            </TouchableOpacity>
                        ) : (
                            <TouchableOpacity onPress={addAdminGroup}>
                                <Text style={{ color: "#EC6138" }}>完成</Text>
                            </TouchableOpacity>
                        )
                    ),
                }}
            />
            <View style={{ paddingHorizontal: 12, }}>
               <View>
                   <Text style={styles.groupLeveltext}>群主</Text>
               </View>
               <View style={styles.groupLevelWrap}>
                  <View style={styles.groupLevelLeft}>
                      <View style={styles.groupLevelLeftAvator}>
                          <Image source={{ uri: currentGroupList[0]?.faceURL  }} style={{ width: "100%", height: "100%" }}/>
                      </View>
                      <Text style={styles.groupLevelLeftName}>{ currentGroupList[0]?.nickname }</Text>
                  </View>
                   <TouchableOpacity style={styles.groupLevelRight} onPress={openActionSheet}>
                       <Text style={styles.groupLevelRightText}>{ options[currentGroupInfo?.needVerification] }</Text>
                       <AntDesign name="right" size={12} color="#9E9E9E" />
                   </TouchableOpacity>
               </View>
                <View style={{ marginTop: 30, marginBottom: 8 }}>
                    <Text style={styles.groupLeveltext}>
                        管理员({ computedAdmin() } /10)
                    </Text>
                </View>
                <View style={styles.adminList}>
                    {
                        list.map((item, index) => {
                           if ((item.roleLevel == RoleLevelEnum.Admin && item?.select) || (item.roleLevel == RoleLevelEnum.Nomal && item.select)) {
                               return (
                                   <View style={styles.adminLeft} key={item.userID}>
                                       <View style={styles.adminAvator}>
                                           <Image source={avator} style={{ width: "100%", height: "100%" }} />
                                           {
                                               toggleEdite && (
                                                   <TouchableOpacity onPress={() => removeGroupAdmin(item.userID)} style={styles.increateGroup}>
                                                       <Image  source={increateGroupIcon} style={{ width: "100%", height: "100%" }} />
                                                   </TouchableOpacity>
                                               )
                                           }
                                       </View>
                                       <Text style={styles.adminLeftName}>{ item?.nickname }</Text>
                                   </View>
                               )
                           };
                        })
                    }
                    {
                        enableAdmin() < 10 && (
                            <TouchableOpacity onPress={goGroupAdmin}>
                                <View style={styles.addAdmin}>
                                    <View style={styles.addAdminIcon}>
                                        <Image source={addGroupAdmin} style={{ width: "100%", height: "100%" }} />
                                    </View>
                                    <Text style={styles.addAdminText}>添加管理员</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    }
                </View>
            </View>
        </View>

    );
}

const styles = StyleSheet.create({
    groupLeveltext: {
        fontSize: 12,
        color: "#9E9E9E"
    },
    groupLevelWrap: {
        flexDirection: "row",
        backgroundColor: "#fff",
        paddingHorizontal: 10,
        paddingVertical: 8,
        borderRadius: 10,
        marginTop: 8,
    },
    groupLevelLeft: {
        flex: 1,
        flexDirection: "row",
        alignItems: "center"
    },
    groupLevelLeftAvator: {
        width: 40,
        height: 40
    },
    groupLevelLeftName: {
        marginLeft: 10,
    },
    groupLevelRight: {
        alignItems: "center",
        flexDirection: "row",
    },
    groupLevelRightText: {
        color: "#9E9E9E",
        fontSize: 12,
    },
    adminList: {
        backgroundColor: "#FFF",
        borderRadius: 10,
        paddingHorizontal: 10,
        paddingVertical: 12,
    },
    adminAvator: {
        width: 40,
        height: 40,
        position: "relative",
    },
    adminLeft: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: 20,
    },
    adminLeftName: {
        marginLeft: 10,
    },
    addAdmin: {
        flexDirection: "row",
    },
    addAdminIcon: {
        width: 16,
        height: 16,
    },
    addAdminText: {
        marginLeft: 10,
    },
    increateGroup: {
        width: 18,
        height: 18,
        position: "absolute",
        right: -8,
        top: 0,
    },
});
